from urllib.request import urlopen,urlretrieve
from urllib.error import HTTPError,URLError
from bs4 import BeautifulSoup
import requests 

import smtplib 
from email.mime.text import MIMEText

# urlretrieve 用来下载文件 

def get_bs4_obj(url)->BeautifulSoup:
    '''根据url获取一个bs4对象'''

    try:
        html = urlopen(url)
        print('html',type(html))
    except (HTTPError,URLError) as e:
        print("11",e)
        return None
    
    try:
        bs4Obj = BeautifulSoup(html.read(),'html.parser') #指定解析器 不然会报警告 2017年6月27日17:38:47 
    except AttributeError as e:
        print("22",e)
        return None
    return bs4Obj
    

def download_image(url):
    '''获取图灵图书的封面图片'''
    bs4 = get_bs4_obj(url)
    imgTags = bs4.findAll(r"img")
    saveImgs = [imgTags[i] for i in range(0,5)]
    for img in saveImgs:
        #print(type(img.attrs),img.attrs['src']) # Tag 实例的attrs是一个字典 获取标签的所有属性-值
        imgSrc = img.attrs['src']
        name = re.split("\/",imgSrc)[-1] + ".jpg"
        name = os.path.join('collectImgs',name)
        print("开始下载:",imgSrc)
        pic = requests.get(imgSrc) #获取到图片的内容
        print("保存在:",name,'pic',type(pic))
        with open(name,'wb') as f: #二进制打开文件 
            f.write(pic.content) #把图片写入


def send_email(subject,body):
    '''
        发送邮件 (还没完善)
        http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432005226355aadb8d4b2f3f42f6b1d6f2c5bd8d5263000
    '''
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['from'] = 'zhouhonghui@37.com'
    msg['to'] = 'zhouhonghui@37.com'

    s = smtplib.SMTP('smtp.37.com')
    s.send_message(msg)
    s.quit()